import { message } from '@/components/XtxUI';
import router from '@/router';
import type { OrderCreate, OrderDetail, OrderPre } from '@/types';
import { http } from '@/utils/request';
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { useCartStore } from './cart';

// 定义新 Store
export const useOrderStore = defineStore('order', () => {
  const orderPre = ref<OrderPre>();
  const getOrderPre = async () => {
    const res = await http<OrderPre>('GET', '/member/order/pre');
    orderPre.value = res.data.result;
  };
  const reqAddAddress = (data: object) => {
    const res = http('POST', '/member/address', data);
  };
  const reqFindAddAddress = () => {
    const res = http('GET', '/member/address');
  };
  // 提交(创建)订单
  const createOrder = async (data: object) => {
    // 创建订单接口
    const res = await http<OrderCreate>('POST', '/member/order', data);
    console.log('POST', '/member/order', res);
    // 成功提醒用户
    message({ type: 'success', text: '下单成功~' });
    // 主动更新购物车列表
    const cart = useCartStore();
    cart.getCartList();
    // 🎯跳转到支付页，传递订单id
    router.replace(`/member/pay?orderId=${res.data.result.id}`);
  };
  // 获取订单详情
  const orderDetail = ref<OrderDetail>();
  const getOrderDetail = async (orderId: string) => {
    const res = await http<OrderDetail>('GET', `/member/order/${orderId}`);
    orderDetail.value = res.data.result;
  };
  // 记得 return
  return {
    orderPre,
    getOrderPre,
    reqAddAddress,
    reqFindAddAddress,
    createOrder,
    getOrderDetail,
    orderDetail,
  };
});
